package testrc

import (
	"net/http"
	"sort"

	"fmt"

	"encoding/xml"

	"strconv"

	"awfan.cn/utils"
	"gopkg.in/mgo.v2"
	"gopkg.in/mgo.v2/bson"
)

func query(format, uid, id string, w http.ResponseWriter, db *mgo.Database) {
	if !bson.IsObjectIdHex(uid) {
		utils.WriteError(format, 405, fmt.Sprintf("#uid is wrong format: '%v'", id), w)
		return
	}
	if !bson.IsObjectIdHex(id) {
		utils.WriteError(format, 405, fmt.Sprintf("#id is wrong format: '%v'", id), w)
		return
	}

	c := db.C(utils.PkgName(TESTRC_XML{}))

	d := TESTRC_XML{}
	q := c.Find(bson.M{"test.id": id, "member.id": uid})

	var count int
	var e error
	if count, e = q.Count(); e != nil {
		utils.WriteError(format, 404, e.Error(), w)
		return
	}
	if count <= 0 {
		utils.WriteData(format, d, w)
		return
	}

	if e = q.One(&d); e != nil {
		utils.WriteError(format, 404, e.Error(), w)
		return
	}

	utils.WriteData(format, d, w)
}

// not use
func exist(format, uid, id string, w http.ResponseWriter, db *mgo.Database) {
	if !bson.IsObjectIdHex(uid) {
		utils.WriteError(format, 405, fmt.Sprintf("#uid is wrong format: '%v'", id), w)
		return
	}
	if !bson.IsObjectIdHex(id) {
		utils.WriteError(format, 405, fmt.Sprintf("#id is wrong format: '%v'", id), w)
		return
	}

	c := db.C(utils.PkgName(TESTRC_XML{}))

	q := c.Find(bson.M{"test.id": id, "member.id": uid})

	var count int
	var e error
	if count, e = q.Count(); e != nil {
		utils.WriteError(format, 404, e.Error(), w)
		return
	}

	type existrecord struct {
		XMLName xml.Name `xml:"record" json:"-" bson:"-"`
		Exist   bool     `xml:"exist" json:"exist"`
	}

	utils.WriteData(format, existrecord{Exist: count > 0}, w)
}
func report(format, uid, times string, w http.ResponseWriter, db *mgo.Database) {
	if !bson.IsObjectIdHex(uid) {
		utils.WriteError(format, 405, fmt.Sprintf("#uid is wrong format: '%v'", uid), w)
		return
	}
	var t int
	var e error
	if t, e = strconv.Atoi(times); e != nil {
		utils.WriteError(format, 404, e.Error(), w)
		return
	}

	c := db.C(utils.PkgName(TESTRC_XML{}))

	q := c.Find(bson.M{"times": t, "member.id": uid})

	d := TESTRCS_XML{}

	if e = q.All(&d.Tests); e != nil {
		utils.WriteError(format, 404, e.Error(), w)
		return
	}

	utils.WriteData(format, d, w)
}
func times(format, uid string, w http.ResponseWriter, db *mgo.Database) {
	if !bson.IsObjectIdHex(uid) {
		utils.WriteError(format, 405, fmt.Sprintf("#uid is wrong format: '%v'", uid), w)
		return
	}

	c := db.C(utils.PkgName(TESTRC_XML{}))

	q := c.Find(bson.M{"member.id": uid})

	var e error
	type drecord struct {
		XMLName xml.Name `xml:"record" json:"-"`
		Times   []int    `xml:"times" json:"times"`
	}

	result := drecord{}

	if e = q.Distinct("times", &result.Times); e != nil {
		utils.WriteError(format, 404, e.Error(), w)
		return
	}

	sort.Ints(result.Times)

	utils.WriteData(format, result, w)
}
